<?php

namespace App\Admin\Actions\Grid\GoodsOrder;

use App\Models\GoodsLogistic;
use App\Models\GoodsOrder;
use Carbon\Carbon;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Widgets\Modal;
use Illuminate\Http\Request;

class CreateOrderDelivery extends BatchAction
{
    /**
     * @return string
     */
    protected $title = '订单发货';

    public function handle(Request $request)
    {
        $keys = $this->getKey();
        $logistics = [];
        foreach ($keys as $order_id){
            $logistics[] = [
                'good_order_id' => $order_id,
                'messagesystem'       => 'yifahuo',
                'time'          => now()
            ];
            //自动写入取件物流信息
            $logistics[] = [
                'good_order_id' => $order_id,
                'messagesystem'       => 'delivery',
                'time'          => Carbon::now()->addHours(rand(1,3))->addMinutes(rand(1,59))->addSeconds(rand(1,59))
            ];
            $logistics[] = [
                'good_order_id' => $order_id,
                'messagesystem'       => 'pickup',
                'time'          => Carbon::now()->addHours(rand(4,5))->addMinutes(rand(1,59))->addSeconds(rand(1,59))
            ];
        }
        GoodsOrder::query()->whereIn('id',$keys)->update(['order_status' => GoodsOrder::ORDER_NOT_RECEIVED,'delivery_time'=>now()]);
        GoodsLogistic::insert($logistics);

        return $this
            ->response()
            ->success(trans('admin.succeeded'))
            ->refresh();
    }

    protected function getModalScript(): string
    {
        return <<<JS
var key = {$this->getSelectedKeysScript()}
$('#batch-ids').val(key);
/*
$('.field_payment_address_id').change(function (){
    var id = $(this).val();
    $.ajax({
        type: 'GET',
        url: '/admin/payment-address-key',
        data: {'id':id},
        dataType: 'json',
        success: function (data){
            $(".field_key").val(data.data.key)
        }
    });

});
 */
JS;

    }
}
